# encoding=utf-8
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .models import *
from .verify import *

# Create your views here.


@verify_control
def api_login(request):
    """
        @author: Dong Haiming
        @date: 2018/10/11
        提交过来的数据{'user': 'XXX', 'pswd':'*****'}
    """
    info = dict(request.POST)
    user, pswd = info["user"][0], info["pswd"][0]
    try:
        username = User.objects.get(user_name=user)
    except User.DoesNotExist:
        return HttpResponse("请检查用户名和密码")
    else:
        if username.user_password == pswd:
            return HttpResponse("登陆成功")
        else:
            return HttpResponse("请检查用户名和密码")


@verify_api
def api_register(request):
    """
        @author: Dong Haiming
        @date: 2018/10/12
        注册接口：提交的数据类型为{'user':'xxxx','pswd':'xxxx'}
        注意：账号密码最多为18位
        使用方法：
        requests.post('http://127.0.0.1:8000/login/register/',
                      data = {'user':'xxxx','pswd':'xxxx'},
                      )
        返回：
        “注册成功”则写入数据库成功
        '帐号已存在'，
        '账号或者密码长度大于18'，
        '提交的方法应该是Post'，
        数据库字段：
            duty、user_account、user_password、user_name、
            user_sex、user_identity、user_phone、user_date、user_status

    """
    info = dict(request.POST)
    print(info)

    try:
        duty_code = Duty.objects.get(duty_name=info['duty'][0])
    except User.DoesNotExist:
        return HttpResponse('注册的职务不存在')
    else:
        if info['user_name'][0] != '' or info['user_code'][0] != ''\
                or info['sex'][0] != '' or info['user_id'][0] != '' \
                or info['phone'][0] != '':
            duty_code.user_set.create(user_name=info['user_name'][0],
                                      user_account=info['user_code'][0],
                                      user_sex=info['sex'][0],
                                      user_identity=info['user_id'][0],
                                      user_phone=info['phone'][0],
                                      user_password=info['user_id'][0][-6:])
        else:
            return HttpResponse("输入的内容有空，请重新输入")





